﻿//-----------------------------------------------------------------------
// <copyright company="Microsoft Corporation">
//     Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

namespace Microsoft.DevDiv.Wpf.Samples.Controls
{
    using System.Windows;
    using System.Windows.Input;

    /// <summary>
    /// Helper class for commands
    /// </summary>
    public static class CommandingOperations
    {
        public static bool ExecuteCommand(ICommandSource source, IInputElement defaultCommandTarget)
        {
            bool result = false;

            if (source != null)
            {
                result = ExecuteCommand(source.Command, source.CommandParameter, source.CommandTarget ?? defaultCommandTarget);
            }

            return result;
        }

        public static bool ExecuteCommand(ICommand command, object parameter, IInputElement target)
        {
            bool result = false;

            if (command != null)
            {
                RoutedCommand routedCommand = command as RoutedCommand;
                if (routedCommand != null)
                {
                    if (routedCommand.CanExecute(parameter, target))
                    {
                        routedCommand.Execute(parameter, target);
                        result = true;
                    }
                }
                else
                {
                    if (command.CanExecute(parameter))
                    {
                        command.Execute(parameter);
                        result = true;
                    }
                }
            }

            return result;
        }
    }
}
